//
//  MSFilterHeadView.m
//  MSJD
//
//  Created by 箭军刘 on 2018/10/20.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSFilterHeadView.h"

#import "MSFilterView.h"
#import "MSFilterButton.h"
#import "DropDownView.h"
#import "UIView+Extension.h"

@interface MSFilterHeadView()


@property (weak, nonatomic) IBOutlet UIView *filterViewFirst;
@property (weak, nonatomic) IBOutlet UIView *filterViewSecond;
@property (weak, nonatomic) IBOutlet UIView *filterViewThird;
@property (weak, nonatomic) IBOutlet UIView *filterViewFouth;

// 对应三个下拉框
@property (nonatomic, strong) DropDownView *filterTableView1;
@property (nonatomic, strong) DropDownView *filterTableView2;
@property (nonatomic, strong) DropDownView *filterTableView3;
@property (nonatomic, strong) MSFilterView *filterTableView4;

@property (nonatomic, copy) NSDictionary *filterData;
@property (nonatomic, strong) NSMutableDictionary *filterDic; // 筛选参数选择 key分别为:one, two, three ,four 分别对应4个筛选控件
@property (nonatomic, assign) BOOL isHotel;

@end

@implementation MSFilterHeadView {
    MSFilterButton *_filterOne;
    MSFilterButton *_filterSecond;
    MSFilterButton *_filterThird;
    MSFilterButton *_filterFouth;
    
    // 下拉黑色半透明背景
    UIView *_bgView;

    // 存储 tableView didSelected数据 数据来源：FilterDataTableView
    NSArray *_dataSource1;
    NSArray *_dataSource2;
    NSArray *_dataSource3;
    NSArray *_dataSource4;
    
    NSInteger _selectIndex; // -1为为展示
    NSInteger _tempSelectIndex;
}

+ (instancetype)loadFilterHeadViewWithIsHotel:(BOOL)isHotel {
    MSFilterHeadView *filterHead = [[[NSBundle mainBundle] loadNibNamed:@"MSFilterHeadView" owner:nil options:nil] firstObject];
    filterHead.isHotel = isHotel;
    return filterHead;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    _dataSource1 = @[@{@"id":@(1), @"name":@"1", @"dicts":@[@{@"id":@(11), @"level":@(11), @"name":@"11"},
                                                            @{@"id":@(12), @"level":@(12), @"name":@"12"},
                                                            @{@"id":@(13), @"level":@(13), @"name":@"13"},
                                                            @{@"id":@(14), @"level":@(14), @"name":@"14"}]},
                     @{@"id":@(2), @"name":@"2", @"dicts":@[@{@"id":@(21), @"level":@(21), @"name":@"21"},
                                                            @{@"id":@(22), @"level":@(22), @"name":@"22"},
                                                            @{@"id":@(23), @"level":@(23), @"name":@"23"},
                                                            @{@"id":@(24), @"level":@(24), @"name":@"24"}]},
                     @{@"id":@(3), @"name":@"3", @"dicts":@[@{@"id":@(31), @"level":@(31), @"name":@"31"},
                                                            @{@"id":@(32), @"level":@(32), @"name":@"32"},
                                                            @{@"id":@(33), @"level":@(33), @"name":@"33"},
                                                            @{@"id":@(34), @"level":@(34), @"name":@"34"}]}];
    NSMutableArray *tempDataSource = _dataSource1.mutableCopy;
    [tempDataSource addObject:@{@"id":@(3), @"name":@"3", @"dicts":@[]}];
    _dataSource2 = tempDataSource.copy;
    
    _dataSource3 = @[@{@"key":@"auto", @"title":@"智能排序"},
                     @{@"key":@"score|asc", @"title":@"评分由低到⾼"},
                     @{@"key":@"score|desc", @"title":@"评分由高到低"},
                     @{@"key":@"price|asc", @"title":@"价格由低到高"},
                     @{@"key":@"price|desc", @"title":@"价格由高到低"}];
    _dataSource4 = @[@{@"id":@(41), @"name":@"测试1", @"dicts":@[@{@"id":@(411), @"level":@(411), @"name":@"选择1"},
                                                            @{@"id":@(412), @"level":@(412), @"name":@"选择2"},
                                                            @{@"id":@(413), @"level":@(413), @"name":@"选择3"},
                                                            @{@"id":@(424), @"level":@(414), @"name":@"选择4"}]},
                     @{@"id":@(42), @"name":@"测试2", @"dicts":@[@{@"id":@(411), @"level":@(411), @"name":@"选择1"},
                                                            @{@"id":@(412), @"level":@(412), @"name":@"选择2"},
                                                            @{@"id":@(413), @"level":@(413), @"name":@"选择3"},
                                                            @{@"id":@(414), @"level":@(414), @"name":@"选择4"}]},
                     @{@"id":@(43), @"name":@"测试3", @"dicts":@[@{@"id":@(411), @"level":@(411), @"name":@"选择1"},
                                                            @{@"id":@(412), @"level":@(412), @"name":@"选择2"},
                                                            @{@"id":@(413), @"level":@(413), @"name":@"选择3"},
                                                            @{@"id":@(414), @"level":@(414), @"name":@"选择4"}]},
                     @{@"id":@(44), @"name":@"测试4", @"dicts":@[@{@"id":@(411), @"level":@(411), @"name":@"选择1"},
                                                            @{@"id":@(412), @"level":@(412), @"name":@"选择2"},
                                                            @{@"id":@(413), @"level":@(413), @"name":@"选择3"},
                                                            @{@"id":@(414), @"level":@(414), @"name":@"选择4"},
                                                               @{@"id":@(415), @"level":@(415), @"name":@"选择5"}]}];
    
    
    CGFloat width = CGRectGetWidth(self.filterViewFirst.frame);
    CGFloat height = CGRectGetHeight(self.filterViewFirst.frame);
    _filterOne = [[[NSBundle mainBundle] loadNibNamed:@"MSFilterButton" owner:nil options:nil] firstObject];
    [_filterOne changeTitle:@"附近"];
    [_filterOne setFrame:CGRectMake(0, 0, width, height)];
    _WEAKSELF
    _filterOne.FilterButtonClickBlock = ^{
        [weakSelf filterButtonClickWithIndex:0];
    };
    [self.filterViewFirst addSubview:_filterOne];
    
    _filterSecond = [[[NSBundle mainBundle] loadNibNamed:@"MSFilterButton" owner:nil options:nil] firstObject];
    [_filterSecond changeTitle:@"美食"];
    [_filterSecond setFrame:CGRectMake(0, 0, width, height)];
    _filterSecond.FilterButtonClickBlock = ^{
        [weakSelf filterButtonClickWithIndex:1];
    };
    [self.filterViewSecond addSubview:_filterSecond];
    
    _filterThird = [[[NSBundle mainBundle] loadNibNamed:@"MSFilterButton" owner:nil options:nil] firstObject];
    [_filterThird changeTitle:@"智能排序"];
    [_filterThird setFrame:CGRectMake(0, 0, width, height)];
    _filterThird.FilterButtonClickBlock = ^{
        [weakSelf filterButtonClickWithIndex:2];
    };
    [self.filterViewThird addSubview:_filterThird];
    
    _filterFouth = [[[NSBundle mainBundle] loadNibNamed:@"MSFilterButton" owner:nil options:nil] firstObject];
    [_filterFouth changeTitle:@"筛选"];
    [_filterFouth setFrame:CGRectMake(0, 0, width, height)];
    _filterFouth.FilterButtonClickBlock = ^{
        [weakSelf filterButtonClickWithIndex:3];
    };
    [self.filterViewFouth addSubview:_filterFouth];
    
    _selectIndex = -1;
}

#pragma mark - Event Response

/** 筛选按钮点击  index:0-3 */
- (void)filterButtonClickWithIndex:(NSInteger)index {
    NSLog(@"点击了筛选按钮: index:%ld", index);
    // 修改icon的状态
    if (index == _selectIndex) {
        // 选中的是当前按钮，直接关闭当前界面
        [self dismiss];
        return;
    }
    
    _tempSelectIndex = index;
    if (self.ShowFilterViewBlock) {
        self.ShowFilterViewBlock();
    }
}

#pragma mark - Public Method

- (void)refreshWithFilterInfo:(NSDictionary *)filterInfo {
    // FIXME
    self.filterData = filterInfo;
    
    NSArray *queriesArr = [MSSafeObject ArrayInfo:filterInfo[@"queries"]];
    if (queriesArr.count < 1) {
        self.filterViewFirst.width = 0;
        self.filterViewFirst.hidden = YES;
        
        // 隐藏第二栏
        self.filterViewSecond.width = 0;
        self.filterViewSecond.hidden = YES;
    } else {
        
        NSDictionary *firstDict = queriesArr[0];
        _dataSource1 = [MSSafeObject ArrayInfo:firstDict[@"dicts"]];
        [_filterOne changeTitle:[MSSafeObject stringInfo:firstDict[@"name"]]];
        
        if (queriesArr.count > 1) {
            NSDictionary *secontDic = queriesArr[1];
            _dataSource2 = [MSSafeObject ArrayInfo:secontDic[@"dicts"]];
            [_filterSecond changeTitle:[MSSafeObject stringInfo:secontDic[@"name"]]];
        } else {
            self.filterViewSecond.width = 0;
            self.filterViewSecond.hidden = 0;
        }
    }
    
    // 排序
    if ([MSSafeObject ArrayInfo:filterInfo[@"sorts"]].count > 0) {
        _dataSource3 = [MSSafeObject ArrayInfo:filterInfo[@"sorts"]];
        NSDictionary *defaultSelectDic = [_dataSource3 firstObject];
        [self.filterDic setObject:defaultSelectDic[@"key"] forKey:@"sort"];
//        [_filterThird changeTitle:[MSSafeObject stringInfo:defaultSelectDic[@"title"]]];
    }
    // 热门商圈
//    _dataSource4 = [MSSafeObject ArrayInfo:filterInfo[@"queries"]];
    self.filterViewFouth.width = 0;
    self.filterViewFouth.hidden = YES;
}

- (void)startShowFilterView {
    if (_selectIndex >= 0) {
        MSFilterButton *selectBtn = [self getFilterButtonWithIndex:_selectIndex];
        if (selectBtn) {
            [selectBtn changeStatus:NO];
        }
    }
    MSFilterButton *newSelectBtn = [self getFilterButtonWithIndex:_tempSelectIndex];
    [newSelectBtn changeStatus:YES];
    
    [self prepareUIWithIndex:_tempSelectIndex];
}

- (void)hiddFilterView {
    [self dismiss];
}

- (void)reloatFilterData {
    // 重置数据
    _selectIndex = -1;
    [self removeAllFilterTableView];
    
    [self.filterDic removeAllObjects];
    // 排序
    if ([MSSafeObject ArrayInfo:self.filterData[@"sorts"]].count > 0) {
        NSDictionary *defaultSelectDic = [((NSArray *)self.filterData[@"sorts"]) firstObject];
        [self.filterDic setObject:defaultSelectDic[@"key"] forKey:@"sort"];
    }
}

- (void)removeAllFilterTableView {
    [self.filterTableView1 removeFromSuperview];
    [self.filterTableView2 removeFromSuperview];
    [self.filterTableView3 removeFromSuperview];
    [self.filterTableView4 removeFromSuperview];
    self.filterTableView1=nil;
    self.filterTableView2=nil;
    self.filterTableView3=nil;
    self.filterTableView4 = nil;
}

#pragma mark - Private Method

- (void)prepareUIWithIndex:(NSInteger)index {
    [self prepareBgView];
    _WEAKSELF
    CGFloat viewDuration = (_selectIndex == -1)?0.25:0.0;
    [self hiddenLastTableView];
    CGFloat top = 44.0 + MS_STATUS_HEIGHT + 36.0;
    if (index == 0) {
        if (!self.filterTableView1) {
            MSFilterViewType filterViewType = MSFilterViewTypeOneTable;
            for (NSDictionary *filterDic in _dataSource1) {
                if (filterDic[@"childs"] && [(NSArray *)filterDic[@"childs"] count] > 0) {
                    filterViewType = MSFilterViewTypeMoreTableEqualWidth;
                    break;
                }
            }
            self.filterTableView1 = [[DropDownView alloc] initWithFrame:CGRectMake(0, top, self.width, 0) data:_dataSource1 viewType:filterViewType];
            self.filterTableView1.SelectBlock = ^(NSDictionary *selectFilterDic) {
                [weakSelf selectFilterWithFilterDic:selectFilterDic];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:self.filterTableView1];
        }
//        [UIView animateWithDuration:viewDuration animations:^{
            weakSelf.filterTableView1.height = 200;
//        }];
    } else if (index == 1) {
        if (!self.filterTableView2) {
            MSFilterViewType filterViewType = MSFilterViewTypeOneTable;
            for (NSDictionary *filterDic in _dataSource2) {
                if (filterDic[@"childs"] && [(NSArray *)filterDic[@"childs"] count] > 0) {
                    filterViewType = MSFilterViewTypeMoreTableEqualWidth;
                    break;
                }
            }
            self.filterTableView2 = [[DropDownView alloc] initWithFrame:CGRectMake(0, top, self.width, 0) data:_dataSource2 viewType:filterViewType];
            self.filterTableView2.SelectBlock = ^(NSDictionary *selectFilterDic) {
                [weakSelf selectFilterWithFilterDic:selectFilterDic];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:self.filterTableView2];
        }
//        [UIView animateWithDuration:viewDuration animations:^{
            weakSelf.filterTableView2.height = 200;
//        }];
    } else if (index == 2) {
        if (!self.filterTableView3) {
            self.filterTableView3 = [[DropDownView alloc] initWithFrame:CGRectMake(0, top, self.width, 0) data:_dataSource3 viewType:MSFilterViewTypeOneTable];
            self.filterTableView3.SelectBlock = ^(NSDictionary *selectFilterDic) {
                [weakSelf selectFilterWithFilterDic:selectFilterDic];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:self.filterTableView3];
        }
//        [UIView animateWithDuration:viewDuration animations:^{
            weakSelf.filterTableView3.height = 200;
//        }];
    } else if (index == 3) {
        if (!self.filterTableView4) {
            self.filterTableView4 = [[MSFilterView alloc] initWithFrame:CGRectMake(0, top, self.width, 0) dataSource:_dataSource4 selectData:@{}];
            self.filterTableView4.SaveButtonClickBlock = ^(NSInteger type, NSDictionary * _Nonnull newSelectDic) {
                // 赋值新的筛选参数对象
                [weakSelf selectFilterWithFilterDic:newSelectDic];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:self.filterTableView4];
        }
//        [UIView animateWithDuration:0.25 animations:^{
            self.filterTableView4.height = 200;
//        } completion:^(BOOL finished) {
            [self.filterTableView4 showButton];
//        }];
    }
    _selectIndex = index;
}

#pragma mark - 准备灰色背景图
- (void)prepareBgView {
    if (_bgView) {
        _bgView.height = MS_SCREEN_HEIGHT;
        return;
    }
    CGFloat top = 44.0 + MS_STATUS_HEIGHT + 36.0;
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, top, self.width, MS_SCREEN_HEIGHT)];
    if (@available(iOS 10.0, *)) {
        _bgView.backgroundColor = [UIColor colorWithDisplayP3Red:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.3];
    } else {
        // Fallback on earlier versions
    }
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [_bgView addGestureRecognizer:tap];
    [[UIApplication sharedApplication].keyWindow addSubview:_bgView];
    
}

- (void)dismiss {

    if (self.HiddenFilterBlock) {
        self.HiddenFilterBlock();
    }
    
    UIView *selectTable = nil;
    if (_selectIndex == 0) {
        selectTable = _filterTableView1;
    } else if (_selectIndex == 1) {
        selectTable = _filterTableView2;
    } else if (_selectIndex == 2) {
        selectTable = _filterTableView3;
    } else {
        selectTable = _filterTableView4;
        [_filterTableView4 hiddenButton];
    }
    
    _selectIndex = -1;
    MSFilterButton *selectBtn = [self getFilterButtonWithIndex:_selectIndex];
    [selectBtn changeStatus:NO];
    // 隐藏当前view
    [UIView animateWithDuration:0.25 animations:^{
        selectTable.height = 0;
    } completion:^(BOOL finished) {
        _bgView.height = 0.0;
    }];
}

- (MSFilterButton *)getFilterButtonWithIndex:(NSInteger)index {
    if (index == 0) {
        return _filterOne;
    } else if (index == 1) {
        return _filterSecond;
    } else if (index == 2) {
        return _filterThird;
    } else if (index == 3) {
        return _filterFouth;
    }
    return nil;
}
/** 隐藏上一个tableView */
- (void)hiddenLastTableView {
    switch (_selectIndex) {
        case 0:
        {
            [self.filterTableView1 hiddenView];
        }
            break;
        case 1:
        {
            [self.filterTableView2 hiddenView];
        }
            break;
        case 2:
        {
            [self.filterTableView3 hiddenView];
        }
            break;
        case 3:
        {
            [self.filterTableView4 hiddenButton];
            self.filterTableView4.height = 0.0;
        }
            break;
        default:
            break;
    }
}
/** 选择了某个 */
- (void)selectFilterWithFilterDic:(NSDictionary *)filterDic {
    NSString *key = @"";
    NSString *newName = (filterDic[@"name"]?:(filterDic[@"title"]?:@"未知"));
    if (_selectIndex == 0) {
        key = @"query1";
//        [_filterOne changeTitle:newName];
        NSDictionary *firstDic = [((NSArray *)self.filterData[@"queries"]) firstObject];
        NSNumber *firstId = firstDic[@"id"];
        NSNumber *selectFilterId = filterDic[@"id"];
        // 保存数据
        [self.filterDic setObject:[NSString stringWithFormat:@"%@-%@", firstId, selectFilterId] forKey:key];
    } else if (_selectIndex == 1) {
        key = @"query2";
//        [_filterSecond changeTitle:newName];
        // 保存数据
        NSDictionary *firstDic = [((NSArray *)self.filterData[@"queries"]) objectAtIndex:1];
        NSNumber *firstId = firstDic[@"id"];
        NSNumber *selectFilterId = filterDic[@"id"];
        // 保存数据
        [self.filterDic setObject:[NSString stringWithFormat:@"%@-%@", firstId, selectFilterId] forKey:key];
    } else if (_selectIndex == 2) {
        key = @"sort";
//        [_filterThird changeTitle:newName];
        // 拼接筛选项的参数
        // 保存数据
        [self.filterDic setObject:[MSSafeObject stringInfo:filterDic[@"key"]] forKey:key];
    } else {
//        key = @"query";
//        [_filterFouth changeTitle:newName];
        // 拼接ID string
//        NSMutableString *filterFouthStr = [NSMutableString string];
//        NSArray *keyArr = [filterDic allKeys];
//        for (NSInteger i = 0; i < keyArr.count; i ++) {
//            NSString *idKey = keyArr[i];
//            if (i == 0) {
//                [filterFouthStr appendFormat:@"%@-%@", idKey, filterDic[idKey]];
//            } else {
//                [filterFouthStr appendFormat:@",%@-%@", idKey, filterDic[idKey]];
//            }
//        }
//        [self.filterDic setObject:filterFouthStr.copy forKey:@"query"];
    }
    NSMutableDictionary *tempFilterSelectDic = [NSMutableDictionary dictionaryWithDictionary:self.filterDic];
    if ([[tempFilterSelectDic allKeys] containsObject:@"query1"] ||
        [[tempFilterSelectDic allKeys] containsObject:@"query2"]) {
        NSMutableString *filterQueryStr = [NSMutableString stringWithString:[MSSafeObject stringInfo:tempFilterSelectDic[@"query1"]]];
        if (![MSSafeObject isNull:tempFilterSelectDic[@"query2"]]) {
            if (filterQueryStr.length > 0) {
                [filterQueryStr appendFormat:@",%@", [MSSafeObject stringInfo:tempFilterSelectDic[@"query2"]]];
            } else {
                [filterQueryStr appendFormat:@"%@", [MSSafeObject stringInfo:tempFilterSelectDic[@"query2"]]];
            }
        }
        [tempFilterSelectDic setObject:filterQueryStr.copy forKey:@"query"];
        [tempFilterSelectDic removeObjectForKey:@"query1"];
        [tempFilterSelectDic removeObjectForKey:@"query2"];
    }
    
    if (self.ChangeFilterBlock) {
        self.ChangeFilterBlock(tempFilterSelectDic.copy);
    }
    // 关闭筛选页
    [self dismiss];
}

#pragma mark - Getters

- (NSMutableDictionary *)filterDic {
    if (!_filterDic) {
        _filterDic = [NSMutableDictionary dictionary];
    }
    return _filterDic;
}

#pragma mark -  Memory Method

- (void)dealloc {
    [self removeAllFilterTableView];
    
    NSLog(@"%s", __func__);
}

@end
